package org.example.service.serviceImpl;

import org.example.exception.BusinessException;
import org.example.model.Enum.ItemType;
import org.example.model.Enum.OrderStatus;
import org.example.model.Log;
import org.example.model.OrderModification;
import org.example.model.PoJo.Item;
import org.example.model.PoJo.Order;
import org.example.service.OrderService;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

public class BaseOrderService implements OrderService {
    @Override
    public Order createOrder(List<Item> items, boolean isVIP, LocalDateTime currentTime) throws BusinessException {
        if (items.isEmpty()){
            throw new BusinessException("订单不能为空");
        }

        if (!isMain(items)){
            throw new BusinessException("必须包含主食");
        }

        if (LocalTime.now().isAfter(LocalTime.of(15,0))){
            int coffeeIndex = isCoffee(items);
            if (!(coffeeIndex < 0)){
                items.remove(coffeeIndex);
            }
        }
        double price = activity(items, isVIP);

        if (!(items.size() <= 5)){
            throw new BusinessException("商品数量超限");
        }
        Order order = new Order(UUID.randomUUID().toString()
                ,items,
                OrderStatus.CREATED,
                price,
                currentTime);

        return order;
    }

    //是否订单中包含主食
    private boolean isMain(List<Item> items){
        for (Item item : items) {
            if (item.getType().equals(ItemType.MAIN)){
                return true;
            }
        }
        return false;
    }

    //订单中是否包括冰咖啡，如果有则返回索引
    private int isCoffee(List<Item> items){
        for (int i = 0; i < items.size(); i++) {
            if (items.get(i).getName().equals("冰咖啡")){
                return i;
            }
        }
        return -1;
    }

    /**
     *
     *  活动初效
     */
    private double activity(List<Item> items,boolean isVIP){
        double price = 0;
        //汉堡计数器
        int hamburgerCount = 0;
        //薯条计数器
        int friesCount = 0;
        //记录单独价格
        double hamburgerPrice = 0;
        double friesPrice = 0;

        //重复计数器
        Map<String,Integer> nameCounter  = new HashMap<>();

        for (Item item : items) {
            if (item.getName().equals("汉堡")){
                hamburgerCount++;
                hamburgerPrice = item.getPrice();
                continue;
            }
            if (item.getName().equals("薯条")){
                friesCount++;
                friesPrice = item.getPrice();
                continue;
            }
            //统计商品名称出现次数
            if (item.getType().equals(ItemType.DRINK)){
                nameCounter.put(item.getName(),
                        nameCounter.getOrDefault(item.getName(),0) + 1);

                if (nameCounter.get(item.getName()) >= 2){
                    price = price + (item.getPrice() / 2);
                    nameCounter.remove(item.getName());
                    continue;
                }
            }



            price = price + item.getPrice();
        }
        if (hamburgerCount > friesCount){
            price = price + (25.0 * friesCount);
            hamburgerCount = hamburgerCount - friesCount;
            friesCount = 0;
        }else if (hamburgerCount == friesCount){
            price = price + (25.0 * friesCount) ;
            hamburgerCount = 0;
            friesCount = 0;
        }else {
            price = price + (25.0 * hamburgerCount);
            friesCount = friesCount - hamburgerCount;
            hamburgerCount = 0;
        }

        //计数单独空出来的汉堡和薯条
        price = price + hamburgerPrice * hamburgerCount;
        price = price + friesPrice * friesCount;
        //判断总价
        if (price >= 100 && isNonWeekend()){
            price = price -10;
        }

        //判断是否为vip用户
        if (isVIP){
            price = price * 0.9;
        }
        return price;
    }

    // 判断当前是否是非周末（周一到周五）
    private boolean isNonWeekend() {
        LocalDate today = LocalDate.now();
        DayOfWeek dayOfWeek = today.getDayOfWeek();
        return !(dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY);
    }



    @Override
    public void cancelOrder(String orderId, LocalDateTime currentTime) throws BusinessException {
        MemoryOrderRepository orderRepository = new MemoryOrderRepository();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                orderRepository.updateStatus(orderId, OrderStatus.CANCELLED);
            }
        },1000 * 60 * 31);
    }

    /**
     * 全部修改
     * @param orderId
     */
    @Override
    public Order updateOrder(String orderId,List<Item> userList,boolean isVIP) throws BusinessException {
        MemoryOrderRepository orderRepository = new MemoryOrderRepository();
        if (!isUpdateOrder(orderId,orderRepository)){
            return null;
        }
        Order userOrder = orderRepository.findById(orderId);
        //记录老订单
        OrderModification.itemUpdate.put(userOrder.getOrderId(),userOrder);


        Order orderUpdate = createOrder(userList, isVIP, userOrder.getCreateTime());
        //记录新订单
        OrderModification.itemUpdate.put(orderUpdate.getOrderId(),orderUpdate);


        orderUpdate.setOrderId(userOrder.getOrderId());

        orderRepository.remove(orderId);
        orderRepository.save(orderUpdate);
        orderUpdate.setStatus(OrderStatus.UPDATE);
        //记录修改日志
        Log.updateTime = LocalDateTime.now();
        return orderUpdate;
    }

    /**
     * 修改部分
     * 添加商品
     */
    public Order save(String orderId,List<Item> saveList,boolean isVIP){
        MemoryOrderRepository memoryOrderRepository = new MemoryOrderRepository();
        if (!isUpdateOrder(orderId,memoryOrderRepository)){
            return null;
        }
        Order userOrder = memoryOrderRepository.findById(orderId);
        //记录老订单
        OrderModification.itemUpdate.put(userOrder.getOrderId(),userOrder);

        //获取用户点餐的列表
        List<Item> items = userOrder.getItems();
        saveList.stream().filter(item -> items.add(item)).collect(Collectors.toList());
        Order order = createOrder(items, isVIP, userOrder.getCreateTime());
        //记录新订单
        OrderModification.itemUpdate.put(order.getOrderId(),order);
        order.setOrderId(userOrder.getOrderId());
        order.setStatus(OrderStatus.UPDATE);
        //记录修改日志
        Log.updateTime = LocalDateTime.now();
        return order;
    }

    /**
     *  删除商品或修改部分数量
     */
    public Order remove(String orderId,boolean isVIP,List<Item> removeList){
        MemoryOrderRepository memoryOrderRepository = new MemoryOrderRepository();
        if (!isUpdateOrder(orderId,memoryOrderRepository)){
            return null;
        }
        Order userOrder = memoryOrderRepository.findById(orderId);
        //记录老订单
        OrderModification.itemUpdate.put(userOrder.getOrderId(),userOrder);

        List<Item> items = userOrder.getItems();
        for (int i = 0; i < removeList.size(); i++) {
            for (int j = 0; j < items.size(); j++) {
                if (removeList.get(i).equals(items.get(j))){
                    items.remove(j);
                }
            }
        }
        Order order = createOrder(items, isVIP, userOrder.getCreateTime());
        //记录新订单
        OrderModification.itemUpdate.put(order.getOrderId(),order);
        order.setOrderId(userOrder.getOrderId());
        order.setStatus(OrderStatus.UPDATE);

        //记录修改日志
        Log.updateTime = LocalDateTime.now();
        return order;
    }

    /**
     * 判断订单是否能够修改
     */
    public boolean isUpdateOrder(String orderId,MemoryOrderRepository orderRepository){
        if (orderRepository.findById(orderId) == null) {
            throw new BusinessException("订单不存在");
        }
        if (orderRepository.findById(orderId).getStatus() == OrderStatus.PAID ||
                orderRepository.findById(orderId).getStatus() == OrderStatus.CANCELLED){
            throw new BusinessException("订单已支付或订单已取消");
        }
        return true;
    }


}
